package com.sskj.api.aspect;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import com.sskj.api.annotation.OperationLog;
import com.sskj.api.domain.UserOperationLog;
import com.sskj.api.service.IUserOperationLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Aspect
@Slf4j
public class OperationLogAspect {

    @Autowired
    private IUserOperationLogService userOperationLogService;

    @Pointcut("@annotation(com.sskj.api.annotation.OperationLog)")
    public void logPointCut(){}

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long startTime = System.currentTimeMillis();

        MethodSignature methodSignature = (MethodSignature)point.getSignature();
        Method method = methodSignature.getMethod();
        OperationLog annotation = method.getAnnotation(OperationLog.class);

        UserOperationLog userOperationLog = new UserOperationLog();
        userOperationLog.setUserId(-1L);
        try {
            long userId = StpUtil.getLoginIdAsLong();
            if (userId > 0) {
                userOperationLog.setUserId(userId);
            }
        } catch (NotLoginException ignored) {}

        userOperationLog.setModule(annotation.module());
        userOperationLog.setAction(annotation.action());
        userOperationLog.setCreateTime(LocalDateTime.now());

        try {
            return point.proceed();
        } catch (Exception e) {
            log.error("异常: {}", e.getMessage());
            throw e;
        } finally {
            long duration = System.currentTimeMillis() - startTime;
            userOperationLog.setDuration(duration);
            userOperationLogService.save(userOperationLog);
        }
    }
}
